﻿@model Xms.Web.Customize.Models.EditQueryViewModel
@{
    var mainEntity = Model.EntityList.First();
}

<div class="">

    <div id="collapseTwo" class="panel-collapse collapse in">
        <div class="">
            <form action="/@app.OrganizationUniqueName/customize/@app.ControllerName/@app.ActionName" method="post" id="editform" class="form-horizontal" role="form">
                @Html.AntiForgeryToken()
                @Html.ValidationSummary()
                @Html.HiddenFor(x => x.SolutionId)
                @Html.HiddenFor(x => x.QueryViewId)
                @Html.HiddenFor(x => x.EntityId)
                @Html.HiddenFor(x => x.FetchConfig)
                @Html.HiddenFor(x => x.LayoutConfig)
                <input type="hidden" id="AggregateConfig" name="AggregateConfig" value="@Model.AggregateConfig" />
                <input type="hidden" id="savetype" name="savetype" value="save" />
                <input type="hidden" id="EntityName" name="EntityName" value="@Model.EntityMetaData.Name" />
                <div class="row position-relative">
                    <div class="col-sm-3">

                        <div id="myTabContent" class="tab-content">
                            <div class="tab-pane in active" id="info" style="padding:5px;">
                                <div class="form-group-head"><i class="glyphicon glyphicon-chevron-down"></i>基本信息</div>
                                <div class="form-group ">
                                    @Html.LabelFor(x => x.Name, "名称", new { @class = "col-sm-2 control-label", style = "padding:7px 0 0 0; white-space:nowrap;" })
                                    <div class="col-sm-10" style="padding-right:0;">
                                        @Html.TextBoxFor(x => x.Name, new { @class = "form-control required" })
                                    </div>
                                </div>
                                <div class="form-group  hide">
                                    @Html.LabelFor(x => x.IsDefault, "默认视图", new { @class = "col-sm-2 control-label", style = "padding:7px 0 0 0; white-space:nowrap;" })
                                    <div class="col-sm-10">
                                        <label class="checkbox-inline">
                                            @Html.RadioButtonFor(x => x.IsDefault, true, new { @class = "required" }) 是
                                        </label>
                                        <label class="checkbox-inline">
                                            @Html.RadioButtonFor(x => x.IsDefault, false, new { @class = "required" }) 否
                                        </label>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    <label class="col-sm-2 control-label" for="JsLibrary" style="padding:7px 0 0 0; white-space:nowrap;">Web资源</label>
                                    <div class="col-sm-10" style="padding-right:0;">
                                        <input type="text" class="form-control input-sm lookup" name="jslibrary_text" id="jslibrary_text" />
                                        <input type="hidden" name="jslibrary" id="jslibrary" />
                                    </div>
                                </div>
                                <div class="form-group  hide">
                                    @Html.LabelFor(x => x.IsSimpleFilter, "简单过滤模式", new { @class = "col-sm-2 control-label", style = "padding:7px 0 0 0; white-space:nowrap;" })
                                    <div class="col-sm-10" style="padding-right:0;">
                                        <label class="checkbox-inline">
                                            @Html.RadioButtonFor(x => x.IsSimpleFilter, true, new { @class = "required" }) 启用
                                        </label>
                                        <label class="checkbox-inline">
                                            @Html.RadioButtonFor(x => x.IsSimpleFilter, false, new { @class = "required" }) 禁用
                                        </label>
                                    </div>
                                </div>
                                <div class="form-group ">
                                    @Html.LabelFor(x => x.Description, "描述", new { @class = "col-sm-2 control-label", style = "padding:7px 0 0 0; white-space:nowrap;" })
                                    <div class="col-sm-10" style="padding-right:0;">
                                        @Html.TextAreaFor(x => x.Description, new { @class = "form-control" })
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="TargetFormId" class="col-sm-2 control-label" style="padding:7px 0 0 0; white-space:nowrap;">默认表单</label>
                                    <div class="col-sm-10" style="padding-right:0;">
                                        <select id="TargetFormId" name="TargetFormId" class="form-control" data-value="@Model.TargetFormId"></select>
                                    </div>
                                </div>
                                <div class="form-group-head  pt-2"><i class="glyphicon glyphicon-chevron-down"></i>实体字段<span class="text-info">(可拖到或双击添加)</span></div>
                                <div class="form-group">
                                    <div class="">
                                        <div id="entitydefaultoption" class="hide"><option data-relationship="" data-referencingattributelocalizedname="" value="@Model.EntityId">@Model.EntityMetaData.LocalizedName</option></div>
                                        <select id="entities" class="form-control">
                                            <option data-relationship="" data-referencingattributelocalizedname="" value="@Model.EntityId">@Model.EntityMetaData.LocalizedName</option>
                                        </select>
                                        <div class="" style="height:220px; border:1px solid #eee; border-top:none; overflow-y:scroll;">
                                            <ul id="attributes" class="list-unstyled connectedSortable" data-bind="foreach: items" style="background:#eee; line-height:25px;">
                                                <li class="mutil-list-item" data-bind="text: localizedname, attr: { 'data-name': name, 'data-entityname': entityname, 'data-entitylocalizedname': entitylocalizedname }">
                                                    <span class="glyphicon glyphicon-screenshot"></span>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-9">
                        <div class="tab-pane" id="buttons">
                            <div class="">
                                <div class="pl-3">
                                    <div class="form-group-head"><i class="glyphicon glyphicon-chevron-down"></i>@app.T["queryview_buttons"]</div>
                                    <span class="">
                                        <label class="checkbox-inline" style="padding-top:0;">
                                            @Html.RadioButtonFor(x => x.IsCustomButton, false, new { @class = "required" }) @app.T["queryview_allbutton"]
                                        </label>
                                        <label class="checkbox-inline" style="padding-top:0;">
                                            @Html.RadioButtonFor(x => x.IsCustomButton, true, new { @class = "required" }) @app.T["queryview_custombutton"]
                                        </label>
                                    </span>
                                </div>
                            </div>
                        </div>
                        <div class="clearfix pt-5">

                            <div class="col-sm-12" id="tableReWidth">
                                <div class="form-group-head"><i class="glyphicon glyphicon-chevron-down"></i>列表排版</div>
                                <div class="btn-group">
                                    <button type="button" class="btn btn-info btn-xs" onclick="moveColumn('before')" title="左移">
                                        <span class="glyphicon glyphicon-arrow-left"></span> 左移
                                    </button>
                                    <button type="button" class="btn btn-info btn-xs" onclick="moveColumn('after')" title="右移">
                                        <span class="glyphicon glyphicon-arrow-right"></span> 右移
                                    </button>
                                    <button type="button" class="btn btn-info btn-xs" onclick="removeColumn()" title="删除">
                                        <span class="glyphicon glyphicon-trash"></span> 删除
                                    </button>
                                    <button type="button" class="btn btn-info btn-xs" onclick="openFilter()" title="过滤条件">
                                        <span class="glyphicon glyphicon-filter"></span> 过滤条件
                                    </button>
                                    <button type="button" class="btn btn-info btn-xs" onclick="openSortModal()" title="排序">
                                        <span class="glyphicon glyphicon-sort"></span> 排序
                                    </button>
                                </div>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-condensed tableResize-box" id="editFormTable" style="width:auto;">
                                        <caption></caption>
                                        <thead>
                                            <tr id="views" class="connectedSortable" style="height:30px; background:#eee;">
                                                <th class="small text-danger ui-state-disabled shadow hide">从左边将属性拖放到这里</th>
                                                @{var thwidth = 0;}
                                                @foreach (var cell in Model.Grid.Rows[0].Cells)
                                                {
                                                    var k = cell.Name.ToLower();
                                                    var label = cell.Name;
                                                    Xms.Schema.Domain.Attribute attr = null;
                                                    if (cell.EntityName.ToLower().Equals(mainEntity.Name.ToLower()) && cell.Name.IndexOf(".") < 0)
                                                    {
                                                        attr = Model.AttributeList.Find(n => n.EntityId == mainEntity.EntityId && String.Equals(n.Name, k, StringComparison.CurrentCultureIgnoreCase));
                                                        label = attr != null ? attr.LocalizedName : k;
                                                    }
                                                    else
                                                    {
                                                        attr = Model.AttributeList.Find(n => String.Equals(n.EntityName, cell.EntityName, StringComparison.CurrentCultureIgnoreCase) && String.Equals(n.Name, k.Split('.')[1], StringComparison.CurrentCultureIgnoreCase));
                                                        label = attr != null ? attr.LocalizedName + "(" + attr.EntityLocalizedName + ")" : k;
                                                    }
                                                    if (attr == null) { continue; }
                                                    var relationship = cell.Name.IndexOf(".") > 0 ? cell.Name.Split('.')[0] : "";
                                                    thwidth += cell.Width;
                                                    if (!string.IsNullOrWhiteSpace(cell.Label))
                                                    {
                                                        label = cell.Label;
                                                    }
                                                    <th style="width:@(cell.Width+"px")" class="tableHeaderItem" data-name="@attr.Name.ToLower()" data-relationship="@relationship" data-type="@attr.AttributeTypeName" data-entityname="@attr.EntityName" data-entitylocalizedname="@attr.EntityLocalizedName" data-referencedentityid="@attr.ReferencedEntityId" data-width="@cell.Width" data-isvisibled="@(!cell.IsHidden)" data-localizedname="@label" data-label="@cell.Label" data-optionsetid="@attr.OptionSetId" data-attributesid="@attr.AttributeId" data-sorttype="" data-sortnum="">
                                                        <span class="th-label">@label</span>
                                                    </th>

                                                }
                                                @*<th class="small text-danger ui-state-disabled shadow">从左边将属性拖放到这里</th>*@
                                            </tr>
                                            <input type="hidden" id="tableheaderWidth" value="@thwidth" />
                                        </thead>
                                        <tbody>
                                            <tr><td class="small text-muted ui-state-disabled shadow">数据</td></tr>
                                            <tr><td class="small text-muted ui-state-disabled shadow">数据</td></tr>
                                            <tr><td class="small text-muted ui-state-disabled shadow">数据</td></tr>
                                            <tr><td class="small text-muted ui-state-disabled shadow">数据</td></tr>
                                            <tr><td class="small text-muted ui-state-disabled shadow">数据</td></tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="clearfix mb-1 ml-3 mt-2">
                            <div class="addView btn btn-info btn-xs" style="" onclick="addView()"><span class="glyphicon glyphicon-plus"></span> 增加行事件</div>
                        </div>
                        <div class="tab-pane rowcommand-box" id="rowcommand" style="padding:5px;">

                            <div class="well" style="position:relative;display:none;">
                                <span class="removeView glyphicon glyphicon-remove" style="position: absolute;right: 5px;top: 42%;cursor:pointer" onclick="removeView(this)"></span>

                                <div class="rowC-item" style="padding:10px;display: inline-block;">
                                    <label class="text-muted">类型：</label>
                                    <select class="EventType form-control input-sm" style="width: 95px;display: inline;">
                                        <option value="onbinding">行绑定时</option>
                                    </select>
                                </div>
                                <div class="rowC-item" style="padding:10px;display: inline;" class="AttributeName">
                                    <label class="text-muted">逻辑：</label>
                                    <select class="LogicalOperator form-control input-sm" style="width: 70px;display: inline;">
                                        <option value="or">或者</option>
                                        <option value="and">并且</option>
                                    </select>
                                </div>
                                <div style="display: inline-table;" class="rowC-item judgeBox">
                                    <div class="judgeView" style="width:527px;display:inline;">
                                        <div style="padding:10px;display:inline;" class="AttributeName">
                                            <label class="text-muted">字段：</label>
                                            <select class="ziduan form-control input-sm" style="width: 80px;display: inline;"></select>
                                        </div>

                                        <div style="padding:10px;display: inline-block;">
                                            <label class="text-muted">操作符：</label>
                                            <select class="Operator form-control input-sm" style="width: 70px;display: inline;">
                                                <option value="Equel">等于</option>
                                            </select>
                                        </div>
                                        <div style="padding:10px;display: inline-block;">
                                            <label class="text-muted">值：</label>
                                            <span class="Values">
                                                <input type='text' class='form-control' name="value" data-value="" style='' placeholder='输入值' value=''>
                                            </span>
                                        </div>
                                        <span class="addMove glyphicon glyphicon-plus" onclick="checkAdd(this)" style="cursor:pointer;"></span>
                                    </div>
                                </div>
                                <div class="rowC-item" style="padding:10px;display: inline-block;">
                                    <label class="text-muted">动作类型：</label>
                                    <select class="ActionType form-control input-sm" style="width: 90px;display: inline;">
                                        <option value="SetRowBackground">背景色</option>
                                    </select>
                                </div>

                                <div class="ColorBack rowC-item" style="padding:10px;display: inline;">
                                    <div class="actionSet" style="display: inline;" data-key="color">
                                        <label class="text-muted">颜色： </label>
                                        <span class="ColorSite">
                                            <input type='text' class='form-control actioncolor colorpicker' data-value="" style='display: inline;height:30px;width: 70px;' placeholder='输入值' value=''>
                                        </span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="col-sm-2"></div>
                </div>

                <div class="form-group col-sm-12 text-center" id="form-buttons">
                    <button type="button" class="btn btn-primary" onclick="Save('save')"><span class="glyphicon glyphicon-saved"></span> @app.T["save"]</button>
                    <button type="button" class="btn btn-primary" onclick="Save('saveandnew')"><span class="glyphicon glyphicon-floppy-saved"></span> @app.T["saveandnew"]</button>
                    <button type="button" class="btn btn-primary" onclick="Save('saveas')"><span class="glyphicon glyphicon-floppy-save"></span> @app.T["saveas"]</button>
                    <button type="reset" class="btn btn-default" onclick="Reset()"><span class="glyphicon glyphicon-refresh"></span> @app.T["reset"]</button>
                </div>

                <div class="rightModal" id="existsButtons" style="" tabindex="-1">
                    <div class="rightModal-dialog">
                        <div class="rightModal-content">
                            <div class="modal-header">
                                <button type="button" class="close" data-dismiss="modal"
                                        aria-hidden="true">
                                    ×
                                </button>
                                <h4 class="modal-title" id="myModalLabel">
                                    设置按钮
                                </h4>
                            </div>
                            <div class="modal-body">
                                <div class="form-group">
                                    <div class="table-responsive">
                                        <table class="table table-bordered table-condensed">
                                            <thead>
                                                <tr>
                                                    <th style="white-space: nowrap;width:10%;text-align:center;" title="显示">
                                                        <input type="checkbox" name="checkall">
                                                    </th>
                                                    <th style="white-space: nowrap;">按钮</th>
                                                    <th style="white-space: nowrap;">位置</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                @foreach (var item in Model.Buttons)
                                                {
                                                    var flag = Model.ButtonId.NotEmpty() ? Model.ButtonId.Contains(item.RibbonButtonId) : false;
                                                    <tr>
                                                        <td class="text-center">
                                                            <input type="checkbox" name="buttonid" value="@item.RibbonButtonId" @(flag ? " checked" : "") />
                                                        </td>
                                                        <td><a href="javascript:;" class="@item.CssClass"><span class="@item.Icon"></span> @item.Label</a></td>
                                                        <td>@(item.ShowArea == Xms.RibbonButton.Abstractions.RibbonButtonArea.ListHead ? "表头" : "行内")</td>
                                                    </tr>
                                                }
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                            @*<div class="modal-footer">
                                    <button type="button" class="btn btn-default"
                                            data-dismiss="modal">
                                        关闭
                                    </button>
                                </div>*@
                        </div><!-- /.modal-content -->
                    </div><!-- /.modal-dialog -->
                </div><!-- /.modal -->
            </form>
        </div>
    </div>
</div>
<!--排序设置-->
<div class="modal fade" id="sortModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    排序设置
                </h4>
            </div>
            <div class="modal-body ">
                <div class="form-group col-sm-12">
                    <label for="sortparm1" class="col-sm-12">第一排序依据</label>
                    <div class="col-sm-8">
                        <select onchange="changeSort(this)" id="sortparm1" name="sortparm1" class="form-control input-sm">
                            <option value="">默认</option>
                        </select>
                    </div>
                    <div class="col-sm-4">
                        <label><input type="radio" name="sorttype1" value="ascending" checked="checked" />升序</label>
                        <label><input type="radio" name="sorttype1" value="descending" />降序</label>
                    </div>
                </div>
                <div class="form-group col-sm-12">
                    <label for="sortparm2" class="col-sm-12">第二排序依据</label>
                    <div class="col-sm-8">
                        <select onchange="changeSort(this)" id="sortparm2" name="sortparm2" class="form-control input-sm"></select>
                    </div>
                    <div class="col-sm-4">
                        <label>
                            <input type="radio" name="sorttype2" value="ascending" checked="checked" />升序
                        </label>
                        <label><input type="radio" name="sorttype2" value="descending" />降序</label>
                    </div>
                </div>
                <div class="clearfix"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    关闭
                </button>
                <button type="button" class="btn btn-primary" onclick="saveSortParams()">
                    确定更改
                </button>
            </div>
        </div>
    </div>
</div><!-- /.modal -->
<!-- 列参数设置（Modal） -->
<div class="rightModal" id="columnModal" tabindex="-1">
    <div class="rightModal-dialog">
        <div class="rightModal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    列参数
                </h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                    <label for="columnattributename">字段</label>
                    <input id="columnattributename" name="columnattributename" readonly type="text" class="form-control input-sm" />
                </div>
                <div class="form-group">
                    <label for="columnlabel">标签</label>
                    <input id="columnlabel" name="columnlabel" type="text" class="form-control input-sm" />
                </div>
                <div class="form-group">
                    <label for="columnwidth">宽度</label>
                    <input id="columnwidth" name="columnwidth" type="text" class="form-control input-sm" />
                </div>
                <div class="form-group">
                    <label for="columnvisibled">
                        显示
                        <input id="columnvisibled" name="columnvisibled" type="checkbox" />
                    </label>
                </div>
                <div class="form-group">
                    <label for="columnstatistical">统计</label>
                    <select id="columnstatistical" name="columnstatistical" type="text" class="form-control input-sm">
                        <option value="">请选择</option>
                        <option value="Sum">总和</option>
                        <option value="Max">最大值</option>
                        <option value="Min">最小值</option>
                        <option value="Avg">平均值</option>
                    </select>
                </div>
                @*<div class="form-group">
                        <label for="sorttype">排序</label>
                        <select id="sorttype" name="sorttype" class="form-control input-sm">
                            <option value="">请选择</option>
                            <option value="ascending">升序</option>
                            <option value="descending">降序</option>
                        </select>
                    </div>*@
            </div>
            <div class="modal-footer">
                @*<button type="button" class="btn btn-default"
                            data-dismiss="modal">
                        关闭
                    </button>*@
                <button type="button" class="btn btn-primary" onclick="saveColumnParams()">
                    确定更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!-- 过滤条件设置（Modal） -->
<div class="modal fade" id="filterModal" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog" style="width:700px; height:500px;">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    ×
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    过滤条件设置
                </h4>
            </div>
            <div class="modal-body">
                <div class="table-responsive" style="width:650px; height:400px; overflow:auto;">
                    <div class="form-group">
                        <div class="btn-group btn-group-xs">
                            <button type="button" class="btn btn-info" onclick="clearConditions()">
                                <span class="glyphicon glyphicon-trash"></span> 清空
                            </button>
                            <button type="button" class="btn btn-info" onclick="groupConditions('and')">
                                <span class="glyphicon glyphicon-link"></span> "并且"组合
                            </button>
                            <button type="button" class="btn btn-info" onclick="groupConditions('or')">
                                <span class="glyphicon glyphicon-link"></span> "或者"组合
                            </button>
                        </div>
                    </div>
                    <div class="form-group">
                        <table id="filterConditions" class="table table-condensed table-selected">
                            <thead class="hide">
                                <tr>
                                    <th></th>
                                    <th>名称</th>
                                    <th>比较关系</th>
                                    <th>数值</th>
                                </tr>
                            </thead>
                            <tbody></tbody>
                            <tfoot>
                                <tr class="hide filterrow">
                                    <td style="width:10px;">
                                        <input type="checkbox" />
                                    </td>
                                    <td style="width:33%">
                                        <select name="filtername" class="form-control input-sm" onchange="onChangeAttribute(this)"></select>
                                    </td>
                                    <td style="width:33%">
                                        <select name="filteroperator" class="form-control input-sm" defaultselected="eq"><option value="eq" title="等于">等于</option><option value="ne" title="不等于">不等于</option><option value="not-null" title="包含数据">包含数据</option><option value="null" title="不包含数据">不包含数据</option><option value="contains" title="包含" fetchop="like" fetchval="%{0}%">包含</option><option value="doesnotcontain" title="不包含" fetchop="not-like" fetchval="%{0}%">不包含</option><option value="beginswith" title="开头等于" fetchop="like" fetchval="{0}%">开头等于</option><option value="doesnotbeginwith" title="开头不等于" fetchop="not-like" fetchval="{0}%">开头不等于</option><option value="endswith" title="结尾等于" fetchop="like" fetchval="%{0}">结尾等于</option><option value="doesnotendwith" title="结尾不等于" fetchop="not-like" fetchval="%{0}">结尾不等于</option></select>
                                    </td>
                                    <td style="width:33%">
                                        <input type="text" name="filtervalue" class="form-control input-sm" />
                                    </td>
                                </tr>
                                <tr>
                                    <td colspan="4">
                                        <select id="filternamelist" name="filtername" class="form-control input-sm" onchange="addCondition(this)">
                                            <option value="">请选择</option>
                                        </select>
                                    </td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default"
                        data-dismiss="modal">
                    <span class="glyphicon glyphicon-remove"></span>
                    关闭
                </button>
                <button type="button" class="btn btn-primary" onclick="saveFilter()">
                    <span class="glyphicon glyphicon-ok"></span>
                    确定更改
                </button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
@section Header{
    <link rel="stylesheet" href="/content/js/jquery-ui-1.10.3/themes/base/jquery.ui.theme.css?v=@app.PlatformSettings.VersionNumber">
    <link href="/content/js/bootstrap-datepicker-1.5.0/css/bootstrap-datepicker3.min.css?v=@app.PlatformSettings.VersionNumber" rel="stylesheet">
    <link href="/content/css/sumoselect.css?v=@app.PlatformSettings.VersionNumber" rel="stylesheet" />
    <link href="/content/js/colorpicker/spectrum.css?v=@app.PlatformSettings.VersionNumber" rel="stylesheet" />

    <style>
        .ui-state-highlight {
            /*height: 25px;
            line-height: 25px;*/
            width: 50px;
            border-bottom: 3px #000 solid;
            list-style: none;
            height: 50px;
        }

        .selected {
            /*border: 1px solid blue;*/
            background: #d9edf7;
        }

            .selected a {
                font-weight: bolder;
            }

        .table {
            margin-bottom: 0px !important;
        }

        #attributes li {
            cursor: move;
            padding-left: 5px;
            padding-right: 5px;
        }
    </style>
}
@section Scripts {
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.core.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.widget.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.mouse.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.sortable.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.draggable.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-ui-1.10.3/ui/jquery.ui.droppable.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.form.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/jquery.validate.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery-validate/localization/messages_zh.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.metadata.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/xms.utility.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/bootstrap-datepicker-1.5.0/js/bootstrap-datepicker.min.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/bootstrap-datepicker-1.5.0/locales/bootstrap-datepicker.zh-CN.min.js?v=@app.PlatformSettings.VersionNumber" charset="UTF-8"></script>
    <script src="/content/js/filterdialog.js?v=23244_@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/fetch.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/colorpicker/spectrum.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script src="/content/js/jquery.sumoselect.js?v=@app.PlatformSettings.VersionNumber"></script>
    @{await Html.RenderPartialAsync("FetchLabel"); }
    <script src="~/content/js/pages/customize.queryview.js?v=@app.PlatformSettings.VersionNumber"></script>
    <script>
        var savetype = 'save';
        var jslibs = @Html.Raw(Model.WebResources.SerializeToJson(false));
        var QueryObject = @Html.Raw(Model.QueryExpression.SerializeToJson(false));
        var Relationships;
        var AttributesList = [];
        var EntityId = $('#EntityId').val();
        var EntityName=$('#EntityName').val();
        var FetchConfig=JSON.parse($('#FetchConfig').val());
        $(function () {
            Xms.Web._callParentMethod('changeLeftWrapState');
            //编辑时初始排序start
            var Orders=QueryObject.Orders;
            for(var i=0;i<Orders.length;i++){
                var oName=Orders[i].AttributeName;
                if(Orders[i].AttributeName.indexOf('.')==-1){
                    var that=$('#views').find('th[data-relationship=""][data-name="'+oName+'"]');
                    if(Orders[i].OrderType==0){
                        that.attr('data-sorttype','ascending');
                    }else{
                        that.attr('data-sorttype','descending');
                    }
                    if(i==0){
                        that.attr('data-sortnum','one');
                    }else{
                        that.attr('data-sortnum','two');
                    }
                }
                else{
                    var oItem=Orders[i].AttributeName.split('.');
                    var oRelationship=oItem[0];
                    oName=oItem[1];
                    var that=$('#views').find('th[data-relationship="'+oRelationship+'"][data-name="'+oName+'"]');
                    if(Orders[i].OrderType==0){
                        that.attr('data-sorttype','ascending');
                    }else{
                        that.attr('data-sorttype','descending');
                    }
                    if(i==0){
                        that.attr('data-sortnum','one');
                    }else{
                        that.attr('data-sortnum','two');
                    }
                }
            }
            //编辑时初始排序end
            $(".modal").draggable({
                handle: ".modal-header",
                cursor: 'move',
                refreshPositions: false
            });
            var $editform = $('#editform');
            $editform.on('submit', function () {
                saveRowCommandValue();
            })
            //表单验证
            Xms.Web.Form($editform, function (response) {
                if (response.IsSuccess) {
                    if (savetype == 'saveandnew') {
                        location.href = 'createqueryview?entityid=' + $('#EntityId').val() + '&solutionid=' + $('#SolutionId').val();
                    }
                    else {
                        Xms.Web.Alert(true, response.Content);
                    }
                    return;
                }
                Xms.Web.Alert(false, response.Content);
            },'', function () {

                if ($("#views").find('th:not(.shadow)').length <= 0) {
                    Xms.Web.Alert(false, '请至少选择一个字段');
                    return false;
                }
                var $isauthorization = $('#IsAuthorization');
                if ($isauthorization.prop('checked')) {
                    if (!$('#securityUser').val() || $('#securityUser').val() == '') {
                        Xms.Web.Alert(false, "请先勾选角色");
                        return false;
                    }
                }
                var flag = saveRowCommandValue();
                if(flag==false && flag.length!=0){
                    Xms.Web.Alert(false,'请先选择行事件的字段名和操作符');
                    return false;
                }
            });
            $editform.find("input[name=checkall]:not(:disabled)").on('click', null, function () {
                var flag = $(this).prop("checked");
                if (flag) {
                    $editform.find("input[name=buttonid]:not(:disabled)").prop("checked", true);
                    $editform.find("tbody > tr").addClass("active");
                }
                else {
                    $editform.find("input[name=buttonid]:not(:disabled)").removeProp("checked");
                    $editform.find("tbody > tr").removeClass("active");
                }
            });
            $.get(ORG_SERVERURL + '/filter/screenconditions', null, function (data) {
                $('#filterModal').find('.modal-body').replaceWith(data);
            })
            $('body').on('change', 'select[name=filteroperator]', function () {
                var type = $(this).parent().prev().find('option:selected').attr('data-type');
                var attributeid = $(this).parent().prev().find('option:selected').attr('data-attributeid');
                var optionsetid = $(this).parent().prev().find('option:selected').attr('data-optionsetid');
                FilterDialog.bindInput($(this), $(this).parent().next().find('input'), type, attributeid, $('#EntityId').val(), getDdlItems(type),optionsetid,undefined,{multiSelector:true})

            })
            $('#views').find('th:not(.shadow)').each(function(i,n){
                var lihtml='<li class="mutil-list-item" data-relationship="'+$(n).attr('data-relationship')+'" data-referencingattributelocalizedname="'+$(n).attr('data-referencingattributelocalizedname')+'" data-type="'+$(n).attr('data-type')+'" data-name="'+$(n).attr('data-name')+'" data-referencedentityid="'+$(n).attr('data-referencedentityid')+'" data-localizedname="'+$(n).attr('data-localizedname')+'" data-entityname="'+$(n).attr('data-entityname')+'" data-entitylocalizedname="'+$(n).attr('data-entitylocalizedname')+'"><span class="glyphicon glyphicon-screenshot"></span>'+$(n).text()+'</li>';
                var item = {
                    'name': $(n).attr('data-name'),
                    'entityname': $(n).attr('data-entityname')||'',
                    'referencedentityid': $(n).attr('data-referencedentityid')||'',
                    'html': lihtml,
                    'relationship': $(n).attr('data-relationship')||'',
                    'text':$(n).text() || ''
                };
                AttributesList.push(item);
                $('#views').parent().siblings('tbody').find('tr').append('<td class="small text-muted ui-state-disabled">数据</td>');
            });
            $('#views').parent().siblings('tbody').find('td.shadow').addClass('hide');
            $("#attributes, #views").sortable({
                connectWith: ".connectedSortable"
                , placeholder: "ui-state-highlight"
                //, revert: true
                , opacity: 0.3
                //, forcePlaceholderSize: true
                , cursor: "move"
                , cancel: ".ui-state-disabled"
                ,stop:function(){
                    resetTableWidth();
                    resizeTableHead();
                    saveGridConfig();
                }
            }).disableSelection();
            $("#attributes").on("sortreceive", function (event, ui) {
                //console.log(event, ui);
                var old = $("#attributes").find('th');
                old.find('span').removeClass('hide');
                var name = li.attr('data-name').toLowerCase();
                var relationship = li.attr('data-relationship') || '';
                var entityname = li.attr('data-entityname').toLowerCase();
                var datatype = li.attr('data-type').toLowerCase();
                var entitylocalizedname = li.attr('data-entitylocalizedname');
                var referencingattributelocalizedname = li.attr('data-referencingattributelocalizedname') || '';
                var referencingattributename = li.attr('data-referencdattributename') || '';
                var referencedentityid = li.attr('data-referencedentityid') || '';
                var referencingattributename = li.attr('data-referencdattributename') || '';
                var referencedentityid = li.attr('data-referencedentityid') || '';
                var attributesid = li.attr('data-attributesid') || '';
                var optionsetid = li.attr('data-optionsetid') || '';
                var el = $('<li class="mutil-list-item">' + old.text() + '</li>');
                el.attr({ 'data-relationship': relationship,'data-type':datatype, 'data-referencingattributelocalizedname': referencingattributelocalizedname, 'data-name': name, 'data-entityname': entityname,'data-referencingattributename':referencingattributename, 'data-entitylocalizedname': entitylocalizedname,'data-referencedentityid':referencedentityid,'data-attributesid':attributesid,'data-optionsetid':optionsetid, 'data-width': 100, 'data-visibled': true, 'data-sorttype': '' });
                old.replaceWith(el);
                saveGridConfig();

            });
			/*双击列表自动添加到表格里*/
			$("#attributes").on('dblclick','li',function(){
				$("#views").append($(this));
				$("#views").trigger('sortreceive');
				resizeTableHead();
			});
			$("#views").on("sortreceive", function (event, ui) {
                //console.log(event, ui);
                var li = $("#views").find('li');
                li.find('span').addClass('hide');
                var name = li.attr('data-name').toLowerCase();
                var relationship = li.attr('data-relationship') || '';
                var entityname = li.attr('data-entityname').toLowerCase();
                var datatype = li.attr('data-type').toLowerCase();
                if (attributeIsExists(entityname, name, relationship)) return;//已存在
                var entitylocalizedname = li.attr('data-entitylocalizedname');
                var referencingattributelocalizedname = li.attr('data-referencingattributelocalizedname') || '';
                var referencingattributename = li.attr('data-referencdattributename') || '';
                var referencedentityid = li.attr('data-referencedentityid') || '';
                var attributesid = li.attr('data-attributesid') || '';
                var optionsetid = li.attr('data-optionsetid') || '';
                var localizedname = li.attr('data-localizedname') || '字段名';
                //var text = entityname == QueryObject.EntityName.toLowerCase() ? li.text() : li.text() + '(' + entitylocalizedname + ')';
                var text = relationship ? localizedname + '(' + referencingattributelocalizedname + ')' : localizedname;
                var el = $('<th style="width:100px;" class="tableHeaderItem"><span class="th-label">' + text + '</span></th>');
                el.attr({ 'data-relationship': relationship,'data-type':datatype, 'data-referencingattributelocalizedname': referencingattributelocalizedname, 'data-name': name, 'data-entityname': entityname,'data-referencedentityid':referencedentityid,'data-referencingattributename':referencingattributename, 'data-entitylocalizedname': entitylocalizedname, 'data-width': 100,'data-attributesid':attributesid,'data-optionsetid':optionsetid,'data-localizedname':localizedname,'data-label':text, 'data-visibled': true, 'data-sorttype': '' });
                if ($("#views").find('th').length == 1)//如果只有一个占位列，则默认第一个加的排序
                {
                    el.attr({ 'data-sorttype': "ascending", 'data-sortnum': 'one' });
                }
                var item = {
                    'name': name,
                    'entityname': entityname,
                    'html': li.clone(),
                    'relationship': relationship,
                    'text':text
                    ,'localizedname':localizedname
                };
                AttributesList.push(item);

               // var tableWidth = 0;
                //$("#views").find('th:not(".shadow")').each(function () {
                //    tableWidth += $(this).outerWidth();
                //});
                //tableWidth += 100;
               // console.log('tableWidth', tableWidth);
			    //$("#views").parents('table').width(tableWidth);
                resetTableWidth();
                resizeTableHead();
                if ($("#views").find('th').length <= 1) {
                    $("#views").append(el);
                    li.remove();
                }
                else {
                    li.replaceWith(el);
                }
                $("#views").parents('table').find('tbody tr').append('<td class="small text-muted ui-state-disabled">数据</td>');
                $("#views").parents('table').find('.shadow').addClass('hide').width(0);
                saveGridConfig();

                  //  addAttributeToInput();

            });
            $("#views").on("sortremove", function (event, ui) {
                var td = $("#views").parents('table').find('tbody tr').find('td:last');
                if (td) td.remove();
                if ($("#views").find('th:not(.shadow)').length == 0)
                    $("#views").parents('table').find('.shadow').removeClass('hide');
                saveGridConfig();
            });

            $.when(loadEntities()).done(loadAttributes(function () {
                $('#renderBody').css('margin-bottom', 10);
                setTimeout(function () {
                  $.fullHeight($('#attributes').parent(), -52);
                },100)
            }));
            loadFilterAttributes();

            //列表列选中
            $("#views").on('click', 'th', function () {
                $(this).parent().siblings().removeClass('selected');
                $(this).parent().addClass('selected');
                setTimeout(function () {
                    editColumnParams();
                }, 16.77);

            });
            $("#views").on('click', 'th', function () {
                $("#views").find('th').removeClass('selected');
                $(this).toggleClass('selected');
            });
            //过滤条件行单击时选中
            //Xms.Web.TableSelected('.table-selected', '.filterrow');
            $('#filterConditions').on('click', ':checkbox', function (e) {//input[name=filtergroup]
                var ischecked = $(this).prop('checked');
                if (ischecked) {
                    $(this).parents('tr').first().addClass('active');
                }
                else {
                    $(this).parents('tr').first().removeClass('active');
                }
            });
            $('#entities').on('change', null, function (e) {
                loadAttributes();
            });
            //按钮
            $('#editform').on('click', 'input[name=iscustombutton]', function (e) {
                var flag = $(this).val();
                if (flag == 'True') {
                    $('#columnModal').removeClass('in');
                    $('#existsButtons').addClass('in');
                }
                else {
                    $('#existsButtons').removeClass('in');
                }
            });

            resetTableWidth();
            resizeTableHead();

            getFormsList($('#EntityId').val(), $('#TargetFormId'),false,function(){
                var _value = $('#TargetFormId').attr('data-value');
                $('#TargetFormId>option[value="'+_value+'"]').prop('selected',true);
            });

            $('#jslibrary_text').lookup({
                disabled: true,
                dialog: function () {
                    Xms.Web.OpenDialog('/customize/WebResource/Dialog?inputid=jslibrary_text', 'selectRecordCallback');
                }
                , clear: function () {
                    $('#jslibrary_text').val('');
                    $('#jslibrary').val('');
                    var _LayoutConfig = $('#LayoutConfig').val();
                    if (_LayoutConfig != "") {
                        var objRowdatas = JSON.parse(_LayoutConfig);
                    } else {
                        var objRowdatas = {};
                    }
                    var jslib = $('#jslibrary');
                        objRowdatas.ClientResources = [];
                        $('#LayoutConfig').val(JSON.stringify(objRowdatas));

                }
            });

            var $rowcommand = $('#rowcommand');
            var rowCommandCn = { LogicalOperat4or: { or: "或者", and: "并且" }, EventType: { onbinding: "行绑定时" }, ActionType: { SetRowBackground: "设置背景" }, Action: { color: '背景色' } }

            $('[data-dismiss="modal"]', '.rightModal').on('click', function () {
                $(this).parents('.rightModal').removeClass('in');
            })

            $("body").on("click", function (e) {
                var target = $(e.target);
              if(target.closest(".rightModal").length != 0||target.closest("input[name=iscustombutton]").length != 0) return;
              $('.rightModal').removeClass('in');

            });
            $('body').on('change','.Operator',function(){
                var type = $(this).parents('.judgeView').find('.ziduan option:selected').attr('data-type');
                var referencedentityid = $(this).parents('.judgeView:first').find('.ziduan').children('option:selected').attr('data-referencedentityid');;
                var attributeid = $(this).parents('.judgeView').find('.ziduan option:selected').attr('data-attributesid');
                var optionsetid = $(this).parents('.judgeView').find('.ziduan option:selected').attr('data-optionsetid');
                FilterDialog.bindInput($(this), $(this).parents('.judgeView').find('input[name=value]'), type, attributeid, referencedentityid, getDdlItems(type),optionsetid,undefined,{multiSelector:true})
                // operatorChange.call(this);
                saveRowCommandValue();
            });
            $('body').on('change','.judgeView .ziduan',function(){
                var operaInput = $(this).parents('.judgeView:first').find('.Operator');
                var datatype = $(this).children('option:selected').attr('data-type');
                loadFilterOperators(operaInput,datatype);
                setTimeout(function(){
                    operaInput.trigger('change');
                    // saveRowCommandValue();
                });

            });

            $('.ActionType').click(function(){
                if($('.ActionType option:selected').text()=="背景色"){
                    $('.ColorBack').show();
                }else{
                    $('.ColorBack').hide();
                }
                saveRowCommandValue();
            })
            if($('.ActionType option:selected').text()=="背景色"){
                $('.ColorBack').show();
            }else{
                $('.ColorBack').hide();
            }

            var _LayoutConfig = $('#LayoutConfig').val();
            var objRowdatas = JSON.parse(_LayoutConfig);
            var RowCommandClass = objRowdatas.RowCommand;
            var jslib = $('#jslibrary');
            if (objRowdatas.ClientResources && objRowdatas.ClientResources.length > 0) {
                $('#jslibrary_text').val($.getArrayByKey(jslibs,'Name').join(','));
                jslib.val(objRowdatas.ClientResources.join(','));
            }
                //return false;

            var loadRowTimer = setInterval(function(){//防止实体字段未加载完时执行行事件数据会出错。
                console.log('loadaddAttributeToInput')
                if(!rowcommondAttributes)return;
                if(rowcommondAttributes){
                    addAttributeToInput();
                    // console.log('views',$('#views').find('th'))

                    clearInterval(loadRowTimer);
                    if(!RowCommandClass || RowCommandClass==''){
                        return false;
                    }

                    initRowCommand(RowCommandClass,$rowcommand);
                    saveRowCommandValue();//防止刷新后重新保存没有值
                }
            }, 100);

            function initRowCommand(datas,_context){

                console.log('initRowCommand',_row);
               // addAttributeToInput();
                //设置值
                for (var i = 0,ilen=datas.length; i <ilen ; i++) {
                    var _row = addView();
                    var iItem = datas[i];
                    $(".LogicalOperator",_row).val(iItem["LogicalOperator"]);
                    $(".EventType",_row).val(iItem["EventType"]);
                    $(".ActionType",_row).val(iItem["ActionType"]);
                    //设置事件具体操作
                    for(var k in iItem['Action']){
                        if(iItem['Action'].hasOwnProperty(k)){
                            $(".actionSet",_row).attr('data-key',k);
                            $(".actionSet",_row).find('.ColorSite').children('input:first').val(iItem["Action"][k]);
                            _row.find('.colorpicker').spectrum("set", iItem["Action"][k]);
                        }
                    }

                    //设置过滤条件
                    for(var j=0,jlen = iItem.Conditions.length; j<jlen;j++){
                        (function(k){
                            var jItem = iItem.Conditions[k];
                            if(j==0){
                                var itemFilter = _row.find('.judgeView:first');
                                var $this = itemFilter;
                            }
                            else{
                                var itemFilter = checkAdd(_row,true);
                                var $this = itemFilter;
                            }

                            var attrInput = $(".ziduan",$this);

                            var operaInput = attrInput.parents('.judgeView:first').find('.Operator');
                            var type = 'nvarchar';
                            console.log('itemFilter',jItem.Operator);
                            //设置字段
                            attrInput.val(jItem["AttributeName"]);

                            //设置操作符
                            var type = attrInput.children('option:selected').attr('data-type');
                            var isRelat = $(".ziduan",$this).find('>option:selected').attr('data-relationship');
                            var referencedentityid = $(".ziduan",$this).find('>option:selected').attr('data-referencedentityid');
                            loadFilterOperators(operaInput,type);
                            var _Operator = jItem.Operator;
                            if(_Operator*1!==0 && _Operator===''){
                                _Operator='';
                            }
                            operaInput.val(jItem.Operator);
                            operaInput.trigger('change');

                            //设置值
                            var _value =jItem.Values;
                            var valInput = attrInput.parents('.judgeView:first').find('input[name=value]');
                            if(_value && _value.length>0){
                                if(type =='lookup' ||type =='customer' ||type =='owner'){

                                    var _entityid = referencedentityid;
                                    if(isRelat){

                                    }
                                    Xms.Web.GetJson('/api/data/Retrieve/ReferencedRecord/' + referencedentityid + '/' + _value.join(',')
                                        ,null,function(response){
                                            console.log('RetrieveReferencedRecord',response)
                                            valInput.val(response.content.name);
                                            valInput.attr('data-value',_value.join(''));
                                        });

                                }else{
                                    valInput.val(_value.join(''));
                                }
                            }
                        })(j);
                    }

                }
            }
        });
    </script>

}